package com.jic.manager.impl;

import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.WorkBookUtil;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.manager.entity.Merchant;
import com.jic.manager.entity.Mestore;
import com.jic.manager.entity.SysRoleUser;
import com.jic.manager.entity.SysUser;
import com.jic.manager.enums.DeptTypeEnum;
import com.jic.manager.enums.SysUserStatusEnums;
import com.jic.manager.enums.SysUserTypeEnums;
import com.jic.manager.mapper.MerchantMapper;
import com.jic.manager.mapper.MestoreMapper;
import com.jic.manager.mapper.SysRoleUserMapper;
import com.jic.manager.request.*;
import com.jic.manager.response.MemStoreResponse;
import com.jic.manager.response.MestoreResponse;
import com.jic.manager.response.StoreImportResponse;
import com.jic.manager.service.MestoreService;
import com.jic.manager.service.SysDeptService;
import com.jic.manager.service.SysUserService;
import com.jic.product.after.request.MeStoreListRequest;
import com.jic.product.after.response.MeStoreListResponse;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//import org.springframework.stereotype.Service;

/**
 * 店铺基本信息
 *
 * @author :
 * @version : v1.0.0
 * @email :
 * @since : 2020-02-26 09:40:07
 */
@Service
public class MestoreServiceImpl implements MestoreService {
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysUserService sysUserService;
    @Resource
    private MestoreMapper mestoreMapper;
    @Resource
    private MerchantMapper merchantMapper;
    @Resource
    private SysRoleUserMapper sysRoleUserMapper;

    @Override
    public long insert(Mestore mestore) {
        long flag = mestoreMapper.insert(mestore);
        return flag;
    }

    @Override
    public long delete(Long id) {
        return mestoreMapper.delete(id);
    }

    @Override
    public long update(Mestore mestore) {
        return mestoreMapper.update(mestore);
    }

    @Override
    public Mestore queryByPrimaryKey(Long id) {
        return mestoreMapper.queryByPrimaryKey(id);
    }

    @Override
    public List<Mestore> query(Mestore mestore) {
        return mestoreMapper.query(mestore);
    }

    @Override
    public PageResult<MemStoreResponse> queryPage(MestoreRequest mestore, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<MestoreRequest> list = mestoreMapper.queryPage(startIndex, pageQuery.getLimit(), mestore);
        long count = mestoreMapper.queryPageCount(mestore);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public MestoreResponse getStoreInfo(MestoreRequest mestoreRequest) {
        return mestoreMapper.getStoreInfo(mestoreRequest);
    }

    @Override
    public PageResult<MestoreResponse> queryStoreInfoPage(MestoreRequest mestoreRequest, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<MestoreResponse> list = mestoreMapper.queryStoreInfoPage(startIndex, pageQuery.getLimit(), mestoreRequest);
        long count = mestoreMapper.queryStoreInfoPageCount(mestoreRequest);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public PageResult<MestoreResponse> queryStoreInfoPageByOrgNumber(MestoreRequest mestoreRequest, Page pageQuery) {
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<MestoreResponse> list = mestoreMapper.queryStoreInfoPageByOrgNumber(startIndex, pageQuery.getLimit(), mestoreRequest);
        long count = mestoreMapper.queryStoreInfoPageByOrgNumberCount(mestoreRequest);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public List<MestoreResponse> queryStoreInfoNoPage(MestoreRequest mestoreRequest) {
        return mestoreMapper.queryStoreInfoNoPage(mestoreRequest);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult<String> editStoreInfo(MestoreRequest mestoreRequest) {
        try {

            Mestore memStore = new Mestore();
            BeanUtils.copyProperties(mestoreRequest, memStore);
            Long id = memStore.getId();
            if (id != null && id != 0) {
                mestoreMapper.update(memStore);
            } else {
                Mestore mestore=new Mestore();
                mestore.setStoreCode(mestoreRequest.getStoreCode());
                List<Mestore> mestoreList=mestoreMapper.query(mestore);
                if(CollectionUtils.isNotEmpty(mestoreList)){
                    return RestResult.error("9999","存在相同的编码");
                }
                //查询是否存在相同账号信息
                List<SysUser> userList = sysUserService.query(new SysUser() {{
                    setAccount(mestoreRequest.getStoreAccount());
                    setDeleteFlag(0);
                }});
                if(CollectionUtils.isNotEmpty(userList)){
                    return RestResult.error("9999","账号已存在");
                }
                Long userId = sysUserService.insertSysUser(new SysUser() {{
                    setAccount(mestoreRequest.getStoreAccount());
                    setPassword(mestoreRequest.getStorePass());
                    setMobile(mestoreRequest.getMobile().toString());
                    setUsername(mestoreRequest.getStoreContactor());
                    setRoleid(mestoreRequest.getRoleId());
                    setStatus(SysUserStatusEnums.PENDING.getName());
                    setType(SysUserTypeEnums.SHOP_USER.getName());
                    setCreateTime(new Date());
                    setCreator(mestoreRequest.getAdminOperate().getOperator());
                    setDeleteFlag(0);
                }});

                sysRoleUserMapper.insert(new SysRoleUser(){{
                    setRoleid(mestoreRequest.getRoleId());
                    setUserid(userId);
                    setStatus("0");
                }});
                //商家id
                if(mestoreRequest.getAdminOperate().getDeptType().getCode().equals(DeptTypeEnum.LPLATFORM_TYPE.getType())){
                    memStore.setMerchantId(mestoreRequest.getDeptId());
                }else{
                    memStore.setMerchantId(mestoreRequest.getAdminOperate().getBusinessId());
                }
                memStore.setUserId(userId);
                memStore.setReviewStatus(0L);
                memStore.setCreator(mestoreRequest.getAdminOperate().getOperator());
                memStore.setCreateTime(new Date());
                memStore.setDeleteFlag(0);
                mestoreMapper.insert(memStore);
            }
            return RestResult.success("成功");
        } catch (Exception e) {
            // TODO
            e.printStackTrace();
            return RestResult.error("9999", e.getLocalizedMessage());
        }
    }

    @Override
    public List<MeStoreListRequest> getStoreList() {
        return mestoreMapper.getStoreList();
    }

    @Override
    public RestResult<PageResult<MestoreResponse>> getByMerchantIds(StoreListGetReuqest storeListGetReuqest) {
        //计算下标
        int startIndex = (storeListGetReuqest.getStart() - 1) * storeListGetReuqest.getLimit();
//        mestoreRequest.setDeptId(mestoreRequest.getAdminOperate().getDeptId());
//        storeListGetReuqest.setMerchantIds(storeListGetReuqest.getAdminOperate().getMerchantIds());
        storeListGetReuqest.setStoreIds(storeListGetReuqest.getAdminOperate().getStoreIds());
        List<MestoreResponse> list = mestoreMapper.getByMerchantIds(startIndex, storeListGetReuqest.getLimit(), storeListGetReuqest);
        long count = mestoreMapper.getByMerchantCount(storeListGetReuqest);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        RestResult result = new RestResult();
        result.setData(pageResult);
        result.setCode("0000");
        return result;
    }


    /*
     * 导入店铺
     * */
    @Override
    public RestResult<PageResult<StoreImportResponse>> importStoreExcel(MultipartFile multipartFile) throws IOException {
        RestResult result = new RestResult();
        StoreImportResponse storeImportResponse = new StoreImportResponse();
        List<Integer> failRows = new ArrayList<>();//失败行数汇总
        List<Integer> repeatRows = new ArrayList<>();//重复行数汇总
        List<SaveDeptListRequestList> saveList = new ArrayList();
        SaveDeptListRequest saveDeptListRequest= new SaveDeptListRequest();
        Merchant merchant = new Merchant();
        Mestore mestore = new Mestore();
        DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
        //转化成workBook对象
        Workbook workBook = WorkBookUtil.createWorkBook(multipartFile.getInputStream(), ExcelTypeEnum.XLS);
        Sheet sheet = workBook.getSheetAt(0);//获取第一个工作表
        int rowCount = sheet.getLastRowNum() + 1;//获取总行数
        for (int i = 1; i < rowCount; i++) {
            try {
                Row row = sheet.getRow(i);
                Cell thirdMerchantCode = row.getCell(3);
                if (CellType.STRING == thirdMerchantCode.getCellTypeEnum()) {
                    mestore.setThirdMerchantCode(thirdMerchantCode.getStringCellValue());//第三方商家编码字符串类型

                    merchant = merchantMapper.getByThirdMerchantCode(thirdMerchantCode.getStringCellValue());
                } else {
                    mestore.setThirdMerchantCode(decimalFormat.format(thirdMerchantCode.getNumericCellValue()));//第三方商家编码number类型

                    merchant = merchantMapper.getByThirdMerchantCode(String.valueOf(decimalFormat.format(thirdMerchantCode.getNumericCellValue())));

                }
//                String thirdMerchantCode = row.getCell(3).getStringCellValue();//获取第三方商家编码判断
//                merchant = merchantMapper.getByThirdMerchantCode(thirdMerchantCode);
                 mestore = createStore(row);
                try {
                    if (merchant != null) {  //判断excel表格内商家编码是否存在于商家表内
                        mestore.setMerchantId(merchant.getId());
                        mestoreMapper.importStore(mestore);
                        //组装sys_dept 数据
                        SaveDeptListRequestList saveDeptListRequestList = new SaveDeptListRequestList();
                        saveDeptListRequestList.setBusinessId(mestore.getId());
                        saveDeptListRequestList.setDeptName(mestore.getStoreName());
                        saveList.add(saveDeptListRequestList);
                        //子平台id
                        saveDeptListRequest.setPBusinessId(merchant.getId());
                        //所属层级
                        saveDeptListRequest.setDeptType(3);
                    } else {
                        failRows.add(new Integer(i+1));
                        continue;
                    }
                } catch (Exception e) {
                    repeatRows.add(new Integer(i + 1));
                }
            } catch (Exception e) {
                // 记录异常数据的行号
                failRows.add(new Integer(i + 1));
            }
        }
        saveDeptListRequest.setSaveDeptListRequestListList(saveList);
        sysDeptService.saveDeptList(saveDeptListRequest);
        storeImportResponse.setFailRows(failRows);
        storeImportResponse.setRepeatRows(repeatRows);
        result.setData(storeImportResponse);
         result.setCode("0000");
        return result;
    }

    @Override
    public RestResult<PageResult<MestoreResponse>> getStorePage(MestorePageRequest mestorePageRequest) {
        //计算下标
        int startIndex =(mestorePageRequest.getStart()-1)*mestorePageRequest.getLimit();
        List<Long> storeIds = mestorePageRequest.getAdminOperate().getStoreIds();
        PageResult pageResult = new PageResult();
        if(storeIds.size()==0){
            pageResult.setRows(new ArrayList());
            pageResult.setTotal(0);
            RestResult result = new RestResult();
            result.setData(pageResult);
            return result;
        }
        mestorePageRequest.setStoreIds(storeIds);
//        mestorePageRequest.setDeptId(mestorePageRequest.getAdminOperate().getDeptId());
        List<MestoreResponse> list = mestoreMapper.getStorePage(startIndex,mestorePageRequest.getLimit(),mestorePageRequest);
        long count =mestoreMapper.getStorePageCount(mestorePageRequest);

        pageResult.setRows(list);
        pageResult.setTotal(count);
        RestResult result = new RestResult();
        result.setData(pageResult);
        return result;
    }

    @Override
    public RestResult<PageResult<MestoreResponse>> findByIds(StoreListGetReuqest storeListGetReuqest) {
        storeListGetReuqest.setStoreIds(storeListGetReuqest.getAdminOperate().getStoreIds());
        storeListGetReuqest.setDeptIdss(storeListGetReuqest.getAdminOperate().getMerchantIds());
        List<MestoreResponse> list = mestoreMapper.findByIds(storeListGetReuqest);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        RestResult result = new RestResult();
        result.setData(pageResult);
        result.setCode("0000");
        return result;
    }

    @Override
    public RestResult<PageResult<MestoreResponse>> getByMercrchantIds(StoreListGetReuqest storeListGetReuqest) {
        //计算下标
        int startIndex = (storeListGetReuqest.getStart() - 1) * storeListGetReuqest.getLimit();
//        mestoreRequest.setDeptId(mestoreRequest.getAdminOperate().getDeptId());
        //TODO 营销调用传参
        storeListGetReuqest.setDeptIds(storeListGetReuqest.getMerchantIds());
        storeListGetReuqest.setStoreIds(storeListGetReuqest.getAdminOperate().getStoreIds());
        List<MestoreResponse> list = mestoreMapper.getByMerchantIds(startIndex, storeListGetReuqest.getLimit(), storeListGetReuqest);
        long count = mestoreMapper.getByMerchantCount(storeListGetReuqest);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        RestResult result = new RestResult();
        result.setData(pageResult);
        result.setCode("0000");
        return result;
    }


    private Mestore createStore(Row row) {
        DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
        Mestore mestore = new Mestore();
        mestore.setStoreName(row.getCell(0).getStringCellValue());//获取店铺名称
        if (row.getCell(1).getStringCellValue().equals("自营")) {
            mestore.setStoreTypes(0L);
            mestore.setStoreType(0L);
        } else {
            mestore.setStoreTypes(1L);
            mestore.setStoreType(1L);
        } //获取店铺类型
        Cell thirdStoreCode = row.getCell(2);
        if (CellType.STRING == thirdStoreCode.getCellTypeEnum()) {
            mestore.setThirdStoreCode(thirdStoreCode.getStringCellValue());//第三方店铺编码字符串类型
            mestore.setStoreCode(thirdStoreCode.getStringCellValue());
        } else {
            mestore.setThirdStoreCode(decimalFormat.format(thirdStoreCode.getNumericCellValue()));//第三方店铺编码number类型
            mestore.setStoreCode(decimalFormat.format(thirdStoreCode.getNumericCellValue()));
        }
        Cell thirdMerchantCode = row.getCell(3);
        if (CellType.STRING == thirdMerchantCode.getCellTypeEnum()) {
            mestore.setThirdMerchantCode(thirdMerchantCode.getStringCellValue());//第三方商家编码字符串类型
        } else {
            mestore.setThirdMerchantCode(decimalFormat.format(thirdMerchantCode.getNumericCellValue()));//第三方商家编码number类型
        }
        mestore.setBusinessProvinceId(row.getCell(4).getStringCellValue());//店铺所属省
        mestore.setBusinessCityId(row.getCell(5).getStringCellValue());//店铺所属市
        mestore.setBusinessRegionId(row.getCell(6).getStringCellValue());//店铺所属区
        mestore.setAddressDetail(row.getCell(7).getStringCellValue());//店铺详细地址
        mestore.setStoreContactor(row.getCell(8).getStringCellValue());//店铺联系人
        if(null != new Double(row.getCell(9).getNumericCellValue()) && new Double(row.getCell(9).getNumericCellValue()) !=0){
            mestore.setMobile((long)row.getCell(9).getNumericCellValue());//店铺联系人手机
        }

        if (row.getCell(10).getStringCellValue().equals("启用")) {
            mestore.setReviewStatus(0L);
        } else {
            mestore.setReviewStatus(1L);
        } //获取店铺状态
        mestore.setCreateTime(new Date());
        mestore.setDeleteFlag(1);
        return mestore;
    }

    @Override
    public MeStoreListResponse queryByStoreCode(String code) {
        return mestoreMapper.queryByStoreCode(code);
    }

    @Override
    public List<Mestore> queryStoreList(MestoreRequest mestoreRequest) {
        return mestoreMapper.queryStoreList(mestoreRequest);
    }
}
